﻿package emusic.api.feeds 
{
	import emusic.api.data.AlbumData;
	import emusic.api.data.SampleTrackData;
	/**
	 * ...
	 * @author Martin Legris ( http://blog.martinlegris.com )
	 */
	public class SampleTrackFeed
	{
		protected var _m3u:Array;
		protected var _pointer:int = 0;
		
		public function SampleTrackFeed(m3u:String) 
		{
			_m3u = m3u.split("\n");
			_pointer = 0;
		}
		
		public function get count():Number { return Math.floor((_m3u.length - 1) / 2); }
		public function get pointer():int { return _pointer; }
		
		public function getAt(idx:Number):SampleTrackData
		{
			var titleExp:RegExp = /#EXTINF:([\d]+),(.*) - (.*)$/i
			var titleLine:String = _m3u[idx * 2 + 1];
			var url:String = _m3u[idx * 2 + 2];
			
			var res:Object = titleExp.exec(titleLine);
			
			var data:SampleTrackData = new SampleTrackData();
			data.name = res[3];
			data.length = parseInt(res[1]);
			data.url = url;
			
			return data;
		}
		
		public function get currentIdx():Number 
		{
			if (_pointer > 0 && _pointer < count+1)
				return _pointer - 1;
			else
				return -1;
		}
		
		public function current():SampleTrackData
		{
			if (_pointer > 0 && _pointer < count+1)
				return getAt(_pointer-1);
			else
				return null;
		}
		
		public function first():SampleTrackData
		{
			return getAt(_pointer = 0);
		}
		
		public function next():SampleTrackData
		{
			if (_pointer < count)
				return getAt(_pointer++);
			else
			{
				_pointer = 0;
				return null;
			}
		}
		
		public function toArray():Array
		{
			var result:Array = [];
			var lastPointer:Number = _pointer;
			first();
			var track:SampleTrackData;
			while (track = next())
				result.push(track);
				
			_pointer = lastPointer;
			
			return result;
		}
		
		public function previous():SampleTrackData
		{
			if (_pointer > 0)
				return getAt(--_pointer);
			else
			{
				_pointer = count - 1;
				return null;
			}
		}
	}
}